<template>
  <div>
    <h1>任务管理页面</h1>
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="请输入任务名称"
          clearable
          class="search-input"
        />
        <el-select v-model="status" placeholder="选择任务状态" class="search-select">
          <el-option label="未开始" value="1"></el-option>
          <el-option label="进行中" value="2"></el-option>
          <el-option label="已完成" value="3"></el-option>
          <el-option label="已逾期" value="4"></el-option>
        </el-select>
        <el-button type="primary" @click="fetchTasks">搜索</el-button>
        <el-button type="success" @click="openCreateDialog">创建任务</el-button>
      </div>

      <!-- 数据表格 -->
    <el-table :data="tasks" border style="width: 100%" v-loading="loading">
      <el-table-column prop="taskName" label="任务名称" />
      <el-table-column label="优先级">
        <template #default="scope">
          {{ getPriorityText(scope.row.priority) }}
        </template>
      </el-table-column>
      <el-table-column prop="assignee" label="负责人" />
      <el-table-column prop="startTime" label="开始时间" />
      <el-table-column prop="endTime" label="结束时间" />
      <el-table-column prop="description" label="任务描述" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusTag(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="openEditDialog(scope.row)">
            修改
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
<el-dialog v-model="editDialogVisible" title="修改任务">
  <el-form :model="editForm" label-width="100px">
    <el-form-item label="任务名称">
      <el-input v-model="editForm.taskName" placeholder="请输入任务名称" />
    </el-form-item>
    <el-form-item label="优先级">
      <el-select v-model="editForm.priority" placeholder="选择优先级">
        <el-option label="高" value="1"></el-option>
        <el-option label="中" value="2"></el-option>
        <el-option label="低" value="3"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="负责人">
      <el-input v-model="editForm.assignee" placeholder="请输入负责人" />
    </el-form-item>
    <el-form-item label="开始时间">
      <el-date-picker
        v-model="editForm.startTime"
        type="datetime"
        placeholder="选择开始时间"
        format="YYYY-MM-DD HH:mm:ss"
      />
    </el-form-item>
    <el-form-item label="结束时间">
      <el-date-picker
        v-model="editForm.endTime"
        type="datetime"
        placeholder="选择结束时间"
        format="YYYY-MM-DD HH:mm:ss"
      />
    </el-form-item>
    <el-form-item label="描述">
      <el-input
        type="textarea"
        v-model="editForm.description"
        rows="4"
        placeholder="请输入描述"
      />
    </el-form-item>
    <el-form-item label="项目">
      <el-input v-model="selectedProjectName" placeholder="项目名称" disabled />
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="editForm.status" placeholder="选择状态">
        <el-option label="未开始" value="1"></el-option>
        <el-option label="进行中" value="2"></el-option>
        <el-option label="已完成" value="3"></el-option>
        <el-option label="已逾期" value="4"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitEdit">保存</el-button>
  </div>
</el-dialog>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 创建任务弹窗 -->
   <el-dialog v-model="createDialogVisible" title="创建任务">
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="任务名称">
          <el-input v-model="createForm.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="createForm.priority" placeholder="选择优先级">
            <el-option label="高" value="1"></el-option>
            <el-option label="中" value="2"></el-option>
            <el-option label="低" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人">
          <el-button type="primary" @click="openUserDialog">选择负责人</el-button>
          <span>{{ createForm.assignee }}</span>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="createForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="createForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            v-model="createForm.description"
            rows="4"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="项目">
          <el-button type="primary" @click="openProjectDialog">选择项目</el-button>
          <span>{{ selectedProjectName }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreate">保存</el-button>
      </div>
    </el-dialog>
        <el-dialog v-model="projectDialogVisible" title="选择项目" width="800px">
      <el-table :data="projects" border style="width: 100%">
        <el-table-column prop="projectName" label="项目名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" @click="selectProject(scope.row)">
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="projectDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 选择负责人弹窗 -->
    <el-dialog v-model="userDialogVisible" title="选择负责人" width="800px">
      <div class="search-bar">
        <el-input
          v-model="userSearchQuery"
          placeholder="请输入用户名"
          clearable
          class="search-input"
        />
        <el-button type="primary" @click="fetchUsers">搜索</el-button>
      </div>
      <el-table
        :data="users"
        border
        style="width: 100%"
        v-loading="loadingUsers"
        @selection-change="handleUserSelection"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="电话" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="selectUser">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';

// 状态
const tasks = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const loading = ref(false);
const searchQuery = ref('');
const status = ref('');
// 选择负责人弹窗状态
const userDialogVisible = ref(false);
const users = ref([]);
const userSearchQuery = ref('');
const loadingUsers = ref(false);
const selectedUser = ref(null);

// 创建任务弹窗状态
const createDialogVisible = ref(false);
const createForm = reactive({
  taskName: '',
  priority: null,
  assignee: '',
  startTime: '',
  endTime: '',
  description: '',
  projectId: null,
});
// 打开选择负责人弹窗
const openUserDialog = () => {
  userDialogVisible.value = true;
  fetchUsers();
};
// 获取用户列表
const fetchUsers = async () => {
  loadingUsers.value = true;
  try {
    const token = localStorage.getItem('token');
    if (!token) throw new Error('未找到 token，请重新登录');

    const response = await axios.get('http://localhost:8080/user/page', {
      params: {
        current: 1,
        size: 10,
        username: userSearchQuery.value || undefined,
      },
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    users.value = response.data.data.records;
  } catch (error) {
    ElMessage.error('获取用户列表失败，请稍后重试');
  } finally {
    loadingUsers.value = false;
  }
};

// 处理用户选择
const handleUserSelection = (selection) => {
  selectedUser.value = selection[0]; // 单选，取第一个选中的用户
};

// 确定选择用户
const selectUser = () => {
  if (selectedUser.value) {
    createForm.assignee = selectedUser.value.username;
    userDialogVisible.value = false;
  } else {
    ElMessage.warning('请选择一个用户');
  }
};
// 获取优先级文本
const getPriorityText = (priority) => {
  switch (priority) {
    case 1:
      return '高';
    case 2:
      return '中';
    case 3:
      return '低';
    default:
      return '未知';
  }
};

// 修改任务弹窗状态
const editDialogVisible = ref(false); // 控制修改任务弹窗的显示状态

const editForm = reactive({
  id: null,
  taskName: '',
  priority: null,
  assignee: '',
  startTime: '',
  endTime: '',
  description: '',
  projectId: null,
  status: null, // 添加状态字段
});


// 项目选择弹窗状态
const projectDialogVisible = ref(false);
const projects = ref([]);
const selectedProjectName = ref('');

// 获取任务列表
const fetchTasks = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    const response = await axios.get('http://localhost:8080/task/page', {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        taskName: searchQuery.value || undefined,
        status: status.value || undefined,
      },
      headers: {
        Authorization: `Bearer ${token}`, // 添加 Authorization 头
      },
    });

    const { records, total: totalRecords } = response.data.data;
    tasks.value = records.map((task) => ({
      ...task,
      startTime: task.startTime ? dayjs(task.startTime).format('YYYY-MM-DD HH:mm:ss') : '未设置',
      endTime: task.endTime ? dayjs(task.endTime).format('YYYY-MM-DD HH:mm:ss') : '未设置',
    }));
    total.value = totalRecords;
  } catch (error) {
    console.error('获取任务数据失败:', error);
    ElMessage.error('获取任务数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 删除任务
const handleDelete = async (task) => {
  try {
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    await ElMessageBox.confirm(
      `确定要删除任务 "${task.taskName}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    await axios.delete(`http://localhost:8080/task/${task.id}`, {
      headers: {
        Authorization: `Bearer ${token}`, // 添加 Authorization 头
      },
    });

    ElMessage.success('任务删除成功');
    fetchTasks();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除任务失败:', error);
      ElMessage.error('删除任务失败，请稍后重试');
    }
  }
};

// 打开创建任务弹窗
const openCreateDialog = () => {
  createDialogVisible.value = true;
};

// 提交创建任务
// 提交创建任务
const submitCreate = async () => {
  try {
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    // 格式化时间
    const formattedCreateForm = {
      ...createForm,
      startTime: createForm.startTime ? dayjs(createForm.startTime).format('YYYY-MM-DDTHH:mm:ss') : null,
      endTime: createForm.endTime ? dayjs(createForm.endTime).format('YYYY-MM-DDTHH:mm:ss') : null,
    };

    await axios.post(
      'http://localhost:8080/task/create',
      formattedCreateForm,
      {
        headers: {
          Authorization: `Bearer ${token}`, // 添加 Authorization 头
          'Content-Type': 'application/json',
        },
      }
    );

    ElMessage.success('任务创建成功');
    createDialogVisible.value = false;
    fetchTasks();
  } catch (error) {
    console.error('创建任务失败:', error);
    ElMessage.error('创建任务失败，请稍后重试');
  }
};


// 提交修改任务
// const submitEdit = async () => {
//   try {
//     const token = localStorage.getItem('token'); // 从 localStorage 获取 token
//     if (!token) {
//       throw new Error('未找到 token，请重新登录');
//     }

//     // 格式化时间
//     const formattedEditForm = {
//       ...editForm,
//       startTime: editForm.startTime ? dayjs(editForm.startTime).format('YYYY-MM-DDTHH:mm:ss') : null,
//       endTime: editForm.endTime ? dayjs(editForm.endTime).format('YYYY-MM-DDTHH:mm:ss') : null,
//     };

//     await axios.put(
//       'http://localhost:8080/task/update',
//       formattedEditForm,
//       {
//         headers: {
//           Authorization: `Bearer ${token}`, // 添加 Authorization 头
//           'Content-Type': 'application/json',
//         },
//       }
//     );

//     ElMessage.success('任务修改成功');
//     editDialogVisible.value = false;
//     fetchTasks(); // 刷新任务列表
//   } catch (error) {
//     console.error('修改任务失败:', error);
//     ElMessage.error('修改任务失败，请稍后重试');
//   }
// };

// 打开修改任务弹窗
const openEditDialog = (task) => {
  Object.assign(editForm, task);
  selectedProjectName.value = task.projectName || '未指定'; // 设置项目名称
  editDialogVisible.value = true;
};

// 提交修改任务
const submitEdit = async () => {
  try {
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    // 格式化时间
    const formattedEditForm = {
      ...editForm,
      startTime: editForm.startTime ? dayjs(editForm.startTime).format('YYYY-MM-DDTHH:mm:ss') : null,
      endTime: editForm.endTime ? dayjs(editForm.endTime).format('YYYY-MM-DDTHH:mm:ss') : null,
    };

    await axios.put(
      'http://localhost:8080/task/update',
      formattedEditForm,
      {
        headers: {
          Authorization: `Bearer ${token}`, // 添加 Authorization 头
          'Content-Type': 'application/json',
        },
      }
    );

    ElMessage.success('任务修改成功');
    editDialogVisible.value = false;
    fetchTasks(); // 刷新任务列表
  } catch (error) {
    console.error('修改任务失败:', error);
    ElMessage.error('修改任务失败，请稍后重试');
  }
};
// 打开选择项目弹窗
const openProjectDialog = async () => {
  try {
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    // 请求项目列表数据
    const response = await axios.get('http://localhost:8080/project/page', {
      params: { current: 1, size: 10 }, // 默认分页参数
      headers: {
        Authorization: `Bearer ${token}`, // 添加 Authorization 头
      },
    });

    // 将项目数据赋值给 projects
    projects.value = response.data.data.records || [];
    projectDialogVisible.value = true; // 打开弹窗
  } catch (error) {
    console.error('获取项目数据失败:', error);
    ElMessage.error('获取项目数据失败，请稍后重试');
  }
};

// 选择项目
const selectProject = (project) => {
  createForm.projectId = project.id;
  selectedProjectName.value = project.projectName;
  projectDialogVisible.value = false;
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchTasks();
};

// 页面加载时获取数据
fetchTasks();

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '未开始';
    case 2:
      return '进行中';
    case 3:
      return '已完成';
    case 4:
      return '已逾期';
    default:
      return '未知状态';
  }
};

// 获取状态标签类型
const getStatusTag = (status) => {
  switch (status) {
    case 1:
      return 'info';
    case 2:
      return 'success';
    case 3:
      return 'warning';
    case 4:
      return 'danger';
    default:
      return 'default';
  }
};
</script>
<style scoped>
.box-card {
  margin: 20px;
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.search-select {
  width: 200px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>